import { createStore } from 'vuex'
import api from '../services/api'

export default createStore({
  state: {
    articles: [],
    categories: [],
    latestArticles: [],
    currentArticle: null,
    currentCategory: null,
    loading: false,
    error: null,
    pagination: null
  },
  mutations: {
    SET_ARTICLES(state, articles) {
      state.articles = articles
    },
    SET_CATEGORIES(state, categories) {
      state.categories = categories
    },
    SET_LATEST_ARTICLES(state, articles) {
      state.latestArticles = articles
    },
    SET_CURRENT_ARTICLE(state, article) {
      state.currentArticle = article
    },
    SET_CURRENT_CATEGORY(state, category) {
      state.currentCategory = category
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    },
    SET_PAGINATION(state, pagination) {
      state.pagination = pagination
    }
  },
  actions: {
    async fetchHomeData({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/api/home')
        console.log('Home data response:', response.data)
        commit('SET_ARTICLES', response.data.articles || [])
        commit('SET_CATEGORIES', response.data.categories || [])
        commit('SET_LATEST_ARTICLES', response.data.latestArticles || [])
        commit('SET_ERROR', null)
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取首页数据失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchCategories({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/api/category/list')
        commit('SET_CATEGORIES', response.data)
        commit('SET_ERROR', null)
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取分类列表失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchArticleDetail({ commit }, id) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/api/article/get/${id}`)
        commit('SET_CURRENT_ARTICLE', response.data)
        commit('SET_ERROR', null)
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取文章详情失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchArticlesByCategory({ commit }, categoryId) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/api/article/category/${categoryId}`)
        commit('SET_ARTICLES', response.data)
        commit('SET_ERROR', null)
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取分类文章失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchCategoryDetail({ commit }, id) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/api/category/get/${id}`)
        const category = response.data
        // 获取该分类的文章
        const articlesResponse = await api.get(`/api/article/category/${id}`)
        commit('SET_CURRENT_CATEGORY', category)
        commit('SET_ARTICLES', articlesResponse.data)
        commit('SET_ERROR', null)
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取分类详情失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchArticlesPaged({ commit }, pageNumber) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/api/article/page/${pageNumber}`)
        const pageData = response.data
        commit('SET_ARTICLES', pageData.items || [])
        commit('SET_PAGINATION', {
          pageNumber: pageData.pageNumber,
          totalPages: pageData.totalPages,
          hasPreviousPage: pageData.hasPreviousPage,
          hasNextPage: pageData.hasNextPage,
          totalItems: pageData.totalItems
        })
        commit('SET_ERROR', null)
        return pageData
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取分页文章失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchCategoryArticlesPaged({ commit }, { categoryId, pageNumber }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/api/category/${categoryId}/page/${pageNumber}`)
        const result = response.data
        
        if (result && result.category && result.articles) {
          commit('SET_CURRENT_CATEGORY', result.category)
          commit('SET_ARTICLES', result.articles.items || [])
          commit('SET_PAGINATION', {
            pageNumber: result.articles.pageNumber || pageNumber,
            totalPages: result.articles.totalPages || 1,
            hasPreviousPage: result.articles.hasPreviousPage || false,
            hasNextPage: result.articles.hasNextPage || false,
            totalItems: result.articles.totalItems || 0
          })
        }
        commit('SET_ERROR', null)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.message)
        console.error('获取分类分页文章失败:', error)
      } finally {
        commit('SET_LOADING', false)
      }
    }
  },
  getters: {
    getArticleById: (state) => (id) => {
      return state.articles.find(article => article.id === id)
    },
    getCategoryById: (state) => (id) => {
      return state.categories.find(category => category.id === id)
    }
  }
})
